/*
Copyright (c) 2023 China Mobile Information Technology Co., Ltd
OpenGauss Operator is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
         http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
*/

package service

import (
	v1 "k8s.io/api/core/v1"
	"k8s.io/klog/v2"
	gsv1 "openGauss-operator/api/v1"
	customClient "openGauss-operator/internal/client"
	"openGauss-operator/internal/util"
)

type ResourceAdjustInterface interface {
	ClusterResourceChange(gs *gsv1.OpenGaussCluster) error
}

type ResourceAdjust struct {
	K8sClient  customClient.K8sClient
	switchover SwitchoverInterface
}

var _ ResourceAdjustInterface = &ResourceAdjust{}

func NewResourceAdjust(client customClient.K8sClient, switchover SwitchoverInterface) ResourceAdjustInterface {
	return &ResourceAdjust{
		K8sClient:  client,
		switchover: switchover,
	}
}

func (r *ResourceAdjust) ClusterResourceChange(gs *gsv1.OpenGaussCluster) error {

	pods, err := r.K8sClient.GetPodList(gs.Namespace, SetPodsLabelsByType(gs, util.PodTypeDB))
	if err != nil || pods == nil {
		klog.Errorf("ClusterResourceChange: Get db pod list err %s", err)
		return err
	}

	crResources := gs.Spec.DBResources
	podsResourceChangeState := make(map[string]bool)
	needChangeResource := false

	for _, value := range pods {
		resources := value.Spec.Containers[0].Resources
		if r.isAdjust(&resources, &crResources) {
			podsResourceChangeState[value.Name] = true
			needChangeResource = true
		} else {
			podsResourceChangeState[value.Name] = false
		}
	}

	if !needChangeResource {
		return nil
	}

	var primaryPods []*v1.Pod
	var standbyPods []*v1.Pod
	clusterState := ""
	primaryPodName := ""

	for _, value := range pods {
		clusterState = r.isClusterAndPodStateNormal(value)
		if clusterState != util.DnStateNormal {
			klog.Errorf("ClusterResourceChange: Abnormal cluster status")
			return nil
		}

		if primaryPodName == "" {
			primaryPodName, err = r.K8sClient.GetPrimaryPodName(gs)
			if err != nil {
				klog.Errorf("Get cluster state err %s", err)
			}
		}

		if value.Name == primaryPodName {
			primaryPods = append(primaryPods, value)
		} else {
			standbyPods = append(standbyPods, value)
		}
	}

	// 删除从节点
	isDeletedStandby, err := r.deletePod(standbyPods, podsResourceChangeState)
	if err != nil {
		return err
	} else {
		if isDeletedStandby {
			klog.Info("ClusterResourceChange: standby pod is deleted")
			return nil
		}
	}

	// 主从切换
	if err := r.switchover.Switchover(gs, standbyPods[0].Name); err != nil {
		return err
	}
	klog.Info("ClusterResourceChange: switchover success")

	// 删除主节点
	isDeletePrimary, err := r.deletePod(primaryPods, podsResourceChangeState)
	if err != nil {
		return err
	} else {
		if isDeletePrimary {
			klog.Info("ClusterResourceChange: primary pod is deleted")
			return nil
		}
	}
	return nil
}

func (r *ResourceAdjust) deletePod(pods []*v1.Pod, podsResourceChangeState map[string]bool) (bool, error) {
	for _, value := range pods {
		if podsResourceChangeState[value.Name] {
			if err := r.K8sClient.DeletePod(value.Name, value.Namespace); err != nil {
				return true, err
			}
			return true, nil
		}
	}
	return false, nil
}

func (r *ResourceAdjust) isClusterAndPodStateNormal(pod *v1.Pod) string {
	if !IsRunningAndReady(pod) {
		return ""
	}

	// Determine if there is a deletiontimestamp flag
	if !pod.DeletionTimestamp.IsZero() {
		return ""
	}

	clusterState, err := r.K8sClient.GetClusterState(pod.Namespace, pod.Name)
	if err != nil {
		return ""
	}
	return clusterState
}

func (r *ResourceAdjust) isAdjust(source *v1.ResourceRequirements, target *gsv1.ResourceList) bool {
	// request
	sourceRequestCpu := source.Requests.Cpu().String()
	sourceRequestMemory := source.Requests.Memory().String()
	tempTargetRequestCpu := target.Requests["cpu"]
	targetRequestCpu := tempTargetRequestCpu.String()
	tempTargetRequestMemory := target.Requests["memory"]
	targetRequestMemory := tempTargetRequestMemory.String()
	// limit
	sourceLimitCpu := source.Limits.Cpu().String()
	sourceLimitMemory := source.Limits.Memory().String()
	tempTargetLimitCpu := target.Limits["cpu"]
	targetLimitCpu := tempTargetLimitCpu.String()
	tempTargetLimitMemroy := target.Limits["memory"]
	targetLimitMemroy := tempTargetLimitMemroy.String()
	if sourceRequestCpu == targetRequestCpu && sourceRequestMemory == targetRequestMemory &&
		sourceLimitCpu == targetLimitCpu && sourceLimitMemory == targetLimitMemroy {
		return false
	}
	return true
}
